package cn.iocoder.yudao.module.qrcode.convert;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.module.qrcode.controller.admin.group.vo.GroupRespVO;
import cn.iocoder.yudao.module.qrcode.dal.dataobject.group.GroupDO;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertMultiMap;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.filterList;

@Mapper
public interface GroupConvert {

    GroupConvert INSTANCE = Mappers.getMapper(GroupConvert.class);

    GroupRespVO covert(GroupDO bean);

    default List<GroupRespVO> convertChildrenList(List<GroupDO> sourceList) {
        if (CollUtil.isEmpty(sourceList)) {
            return Collections.emptyList();
        }
        List<GroupRespVO> convertList = sourceList.stream().map(this::covert).collect(Collectors.toList());
        List<GroupRespVO> childrenList = filterList(
                convertList,
                r -> r.getParentId() != null  && !Objects.equals(GroupDO.PARENT_ID_ROOT, r.getParentId())
        );
        Map<Long, List<GroupRespVO>> parentChildrenMap = convertMultiMap(childrenList, GroupRespVO::getParentId);
        for (GroupRespVO group : convertList) {
            group.setChildren(parentChildrenMap.get(group.getId()));
        }
        return filterList(convertList, r -> Objects.equals(GroupDO.PARENT_ID_ROOT, r.getParentId()));
    }

}
